package com.springcloud.tools.rabbitmq;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author fuc
 * @create 2020-06-16
 */
@Component
@Slf4j
public class MQSender {
  private final RabbitTemplate rabbitTemplate;

  private final RabbitTemplate.ConfirmCallback confirmCallback =
      (correlationData, ack, cause) -> {
        if (ack) {
          log.debug("消息发送到exchange成功,id: [{}]", Objects.requireNonNull(correlationData).getId());
        } else {
          log.debug("消息发送到exchange失败,原因: [{}]", cause);
        }
      };

  private final RabbitTemplate.ReturnCallback returnCallback =
      (message, replyCode, replyText, exchange, routingKey) -> {
        String correlationId = message.getMessageProperties().getCorrelationId();
        log.debug(
            "消息：[{}] 发送失败, 应答码：[{}] 原因：[{}] 交换机: [{}]  路由键: [{}]",
            correlationId,
            replyCode,
            replyText,
            exchange,
            routingKey);
      };

  public MQSender(RabbitTemplate rabbitTemplate) {
    this.rabbitTemplate = rabbitTemplate;
  }

  /** 发送消息方法调用: 构建Message消息 */
  public void send(String exchange, String routingKey, Object message) {
    rabbitTemplate.setMandatory(true);
    rabbitTemplate.setConfirmCallback(confirmCallback);
    rabbitTemplate.setReturnCallback(returnCallback);
    // 全局唯一
    Snowflake snowflake = IdUtil.createSnowflake(1, 1);
    CorrelationData correlationData = new CorrelationData(snowflake.nextIdStr());
    rabbitTemplate.convertAndSend(
        exchange, routingKey, JSON.toJSONString(message), correlationData);
  }
}
